package Net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpClient {

    Socket socket = null;

    public TcpClient() throws IOException {
        //发送给服务器---确定端口号+IP地址
        socket = new Socket("127.0.0.1",8000);
    }

    public void start() throws IOException {
        System.out.println("客户端与服务器已连接!!!");
        Scanner scanner = new Scanner(System.in);//输入请求
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            Scanner scannerNet = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while(true){
                //做出请求
                System.out.print(">");
                String request = scanner.next();
                //将请求发送给服务器
                printWriter.println(request);
                printWriter.flush();//刷新缓冲区
                //根据发出的请求,服务器做出响应==>此时客户端要接收响应
                String response = scannerNet.next();
                System.out.printf("req = %s ; rep = %s\n",request,response);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        TcpClient tcpClient = new TcpClient();
        tcpClient.start();
    }

}
